package com.century.sjt.activity.Topic;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.R;
import com.century.sjt.activity.BaseActivity;
import com.century.sjt.adapter.MySocialZoneAdapter;
import com.century.sjt.entity.Comment;
import com.century.sjt.entity.ItemBean;
import com.century.sjt.entity.Praise;
import com.century.sjt.entity.SjtUser;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.ListViewForScrollView;
import com.century.sjt.widget.TitleBar.SjtTitleBar;
import com.century.sjt.EMChat.utils.EaseUserUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 个人主页
 */
public class HomepageActivity extends BaseActivity {
    private SjtTitleBar titleBar;
    private ImageView ImgBg;
    private ImageView ciHeadimage;
    final List<ItemBean> dataList = new ArrayList<>();

    private MySocialZoneAdapter mySocialZoneAdapter;

    public static Handler mHandler;
//    private Button loadMore;

    private int SEND_LOAD_MORE_NUM = 1;                       //话题翻页的页数

    private com.century.sjt.widget.ListViewForScrollView mListViewForScrollView;

    private SwipeRefreshLayout mSwipeLayout;        //刷新组件
    private Boolean isDataChangeOk = true;        //是否更新成功
    private String userId;

    private List<Comment> mCommentList = new ArrayList<>();
    private List<Praise> mPraiseList = new ArrayList<>();
    private String mPraiseNameList = "";
    private SjtUser mUser;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_homepage);

        userId = getIntent().getExtras().getString("userId");
        mHandler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case 1:
                        mySocialZoneAdapter.notifyDataSetChanged();
                        mSwipeLayout.setRefreshing(false);
//                        Animation animation= AnimationUtils.loadAnimation(getActivity().getBaseContext(), R.anim.alpha);
//                        LayoutAnimationController lac=new LayoutAnimationController(animation);
//                        mListViewForScrollView.setLayoutAnimation(lac);
                        break;
                    case 2:
                        isDataChangeOk = true;
                        dataList.clear();
                        SEND_LOAD_MORE_NUM = 1;
                        loadData();
                        break;
                    case 3:
                        if (isDataChangeOk) {
                            mSwipeLayout.setRefreshing(true);
                            SEND_LOAD_MORE_NUM++;
                            loadData();
                            break;
                        }

                }
            }
        };
        mySocialZoneAdapter=new MySocialZoneAdapter(HomepageActivity.this, dataList, mQueue,mHandler);

        initViews();
        initEvents();
        initDate();
    }

    /**
     * 加载界面
     */
    private void initViews() {
        //控件
        titleBar = (SjtTitleBar) findViewById(R.id.title_bar);

        //--------------> Top 获取   <-----------------
//        titleBar.setBackgroundColor(getResources().getColor(R.color.none_color));
        titleBar.setTitle(getResources().getString(R.string.tab_homepage));
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        mListViewForScrollView = (ListViewForScrollView) findViewById(R.id.lv_my_social_zone_new_mian);
        mSwipeLayout= (SwipeRefreshLayout) findViewById(R.id.my_social_zone_new_refesh);
        ciHeadimage = (ImageView) findViewById(R.id.profile_image);
        ImgBg = (ImageView) findViewById(R.id.homepage_bg);
    }

    /**
     * 初始化事件
     */
    private void initEvents() {
        mListViewForScrollView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ItemBean itemBean = dataList.get(position);
                String topicId = itemBean.topicId;
                Intent intent = new Intent(HomepageActivity.this, MyTopicDetail.class);
                intent.putExtra("topicId", topicId);
                intent.putExtra("option", "");
                startActivity(intent);
                overridePendingTransition(R.animator.in_from_right, R.animator.out_to_left);
            }
        });

        mListViewForScrollView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
                // 当不滚动时
                if (i == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (absListView.getLastVisiblePosition() == absListView.getCount() - 1) {
                        //加载更多功能的代码
                        Message msg = new Message();
                        msg.what = 3;
                        mHandler.sendMessage(msg);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });

        mListViewForScrollView.setAdapter(mySocialZoneAdapter);

        //刷新组件

        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Message msg=new Message();
                msg.what=2;
                mHandler.sendMessage(msg);
            }
        });
        mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);

        //设置顶部头像
        if (null == userId || "".equals(userId)) {

        } else {
//            EaseUserUtils.setUserMobile(userName, tvPhome);
//            EaseUserUtils.setUserNick(userName, tvNick);
            EaseUserUtils.setUserAvatar(this, userId, ciHeadimage);
        }

    }

    /**
     * 初始化数据
     */
    private void initDate() {
        loadData();
    }

    /**
     * 个人主页
     */
    private void loadData() {
        isDataChangeOk = false;
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.friendTopicListHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                isDataChangeOk = true;
                try {
                    TipUtil.log("获取个人主页", response, 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
//                    JSONObject topicList = data.getJSONObject("topicList");
//                    JSONObject user = topicList.getJSONObject("user");
                    if (code.equals("200")) {//成功
//                        Log.e("获取我的话题", response);
                        mPraiseList.clear();
                        mCommentList.clear();
                        mPraiseNameList = "";
                        JSONObject data = res.getJSONObject("data");

                        JSONArray mTopicList = data.getJSONArray("topicList");
                        if(mTopicList.length()!= Constant.PAGESIZE){
                            isDataChangeOk = false;
                        }
                        for(int i =0;i<mTopicList.length();i++){
                            JSONObject topicList= (JSONObject) mTopicList.get(i);
                            String topicId=topicList.getString("sysId");
                            String content=topicList.getString("content");
                            String createDateTime=topicList.getString("createDateTime");
//                            String themePic1=topicList.getString("themePic1");
//                            String themePic2=topicList.getString("themePic2");
//                            String themePic3=topicList.getString("themePic3");
//                            String themePic4=topicList.getString("themePic4");
//                            String themePic5=topicList.getString("themePic5");
//                            String themePic6=topicList.getString("themePic6");
//                            String themePic7=topicList.getString("themePic7");
//                            String themePic8=topicList.getString("themePic8");
//                            String themePic9=topicList.getString("themePic9");
                            String themePic = topicList.getString("themePic");
                            int praiseNum=topicList.getInt("praiseNum");
                            int commentNum=topicList.getInt("commentNum");
                            JSONObject user = topicList.getJSONObject("user");
                            mUser = new SjtUser();
                            mUser.setSysid(user.getString("sysId"));
                            mUser.setNickName(user.getString("nickName"));
                            mUser.setImage(user.getString("image"));
                            String shareUrl = topicList.getString("shareUrl");
//                            Log.e("image1", image);
//                            Log.e("获取话题", createDateTime);
                            JSONArray praiseList = topicList.getJSONArray("praiseList");
                            for (int j = 0;j<praiseList.length();j++){
                                JSONObject praise =(JSONObject) praiseList.get(j);
                                JSONObject auser = (JSONObject) praise.getJSONObject("user");
                                SjtUser user1 = new SjtUser();
                                user1.setSysid(auser.getString("sysId"));
                                user1.setNickName(auser.getString("nickName"));
                                user1.setImage(auser.getString("image"));
                                if (j>0){
                                    String mName = "、"+user1.getNickName();
                                    mPraiseNameList+=mName;
                                }else {
                                    mPraiseNameList+=user1.getNickName()+" ";
                                }

                                Praise praise1 = new Praise();
                                praise1.setSysId(praise.getString("sysId"));
                                praise1.setContent(praise.getString("content"));
                                praise1.setCreateDateTime(praise.getString("createDateTime"));
                                praise1.setUser(user1);
                                mPraiseList.add(praise1);
                            }
                            JSONArray commentList = topicList.getJSONArray("commentList");
                            for (int j = 0;j<commentList.length();j++){
                                JSONObject comment =(JSONObject) commentList.get(j);
                                JSONObject auser = (JSONObject) comment.getJSONObject("user");
                                SjtUser user1 = new SjtUser();
                                user1.setSysid(auser.getString("sysId"));
                                user1.setNickName(auser.getString("nickName"));
                                user1.setImage(auser.getString("image"));
                                Comment comment1 = new Comment();
                                comment1.setSysId(comment.getString("sysId"));
                                comment1.setContent(comment.getString("content"));
                                comment1.setCreateDateTime(comment.getString("createDateTime"));
                                comment1.setUser(user1);
                                mCommentList.add(comment1);
                            }
                            ItemBean itemBean = new ItemBean();
                            itemBean.setCommentList(mCommentList);
                            itemBean.setPraiseList(mPraiseList);
                            itemBean.setPraiseNameList(mPraiseNameList);
                            itemBean.setItemTime(createDateTime);
                            itemBean.setItemContent(content);
                            itemBean.setItemImage(themePic);
                            itemBean.setTopicId(topicId);
                            itemBean.setPraiseNum(praiseNum);
                            itemBean.setCommentNum(commentNum);
                            itemBean.setShareUrl(shareUrl);
                            itemBean.setUser(mUser);
                            Log.e("cc",itemBean.getCommentList().size()+"");
                            dataList.add(itemBean);
                        }
                    } else {//失败
                        isDataChangeOk = false;
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    Toast.makeText(HomepageActivity.this,getResources().getString(R.string.error_service),Toast.LENGTH_LONG).show();
                }
                // 设置适配器
                Message msg=new Message();
                msg.what=1;
                mHandler.sendMessage(msg);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                isDataChangeOk = true;
                SEND_LOAD_MORE_NUM--;
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
                Toast.makeText(HomepageActivity.this,getResources().getString(R.string.error_network),Toast.LENGTH_LONG).show();
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                String num = String.valueOf(SEND_LOAD_MORE_NUM);
                String loginId = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE).getString("userId", "");
                Map<String,String> map = new HashMap<>();
                map.put("paging.currentPage",num);
                map.put("paging.pageSize", Constant.PAGESIZE+"");
                map.put("userId", userId);
                map.put("loginId", loginId);
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                String cookie = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE).getString("cookie", "");
                String rememberMeValue = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE).getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
//                Log.e("cookie", cookieValue);
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);


    }
    @Override
    protected void onDestroy() {
        mQueue.cancelAll(this);
        super.onDestroy();
    }
    @Override
    protected void onResume() {
        super.onResume();

        mListViewForScrollView.setFocusable(false);
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void initData() {

    }
}
